<template>
  <div class="container mx-auto px-4 py-8">
    <div class="max-w-6xl mx-auto space-y-8">
      <!-- 操作说明组件 -->
      <InstructionsCard 
        :instructions="instructions" 
        :image-base-url="'/src/assets'" 
      />

      <!-- 参数配置卡片 -->
      <div class="bg-white rounded-xl shadow-sm p-6">
        <div class="flex items-center mb-6">
          <div class="p-2 bg-blue-50 rounded-lg">
            <Settings class="h-6 w-6 text-blue-500" />
          </div>
          <h2 class="text-xl font-semibold text-gray-800 ml-3">
            接口配置
          </h2>
        </div>
        
        <ConfigurableForm
          v-model="localFormData"
          :config="formConfig"
          @update:modelValue="updateFormData"
        />

        <div class="flex gap-3 mt-6">
          <button 
            class="inline-flex items-center px-4 py-2 text-sm font-medium text-blue-600 bg-blue-50 rounded-lg hover:bg-blue-100 transition-colors duration-200"
            @click="formatSQL"
          >
            <Code class="h-5 w-5 mr-2" />
            格式化SQL
          </button>
          <button 
            class="inline-flex items-center px-4 py-2 text-sm font-medium text-green-600 bg-green-50 rounded-lg hover:bg-green-100 transition-colors duration-200"
            @click="extractFields"
          >
            <FileText class="h-5 w-5 mr-2" />
            提取字段
          </button>
          <button 
            class="inline-flex items-center px-4 py-2 text-sm font-medium text-red-600 bg-red-50 rounded-lg hover:bg-red-100 transition-colors duration-200"
            @click="clearSQL"
          >
            <Trash class="h-5 w-5 mr-2" />
            清空SQL
          </button>
          <button 
            class="inline-flex items-center px-6 py-2 text-sm font-medium text-purple-600 bg-purple-50 rounded-lg hover:bg-purple-100 transition-colors duration-200"
            @click="generateCode"
          >
            <Code class="h-5 w-5 mr-2" />
            生成代码
          </button>
        </div>
      </div>

      <!-- SQL 预览卡片 -->
      <div class="bg-white rounded-xl shadow-sm p-6">
        <div class="flex items-center mb-6">
          <div class="p-2 bg-blue-50 rounded-lg">
            <Code class="h-6 w-6 text-blue-500" />
          </div>
          <h2 class="text-xl font-semibold text-gray-800 ml-3">SQL 预览</h2>
        </div>
        <div class="bg-gray-50 rounded-lg p-4">
          <v-md-preview :text="sqlPreviewContent" />
        </div>
      </div>

      <!-- 字段信息卡片 -->
      <div class="bg-white rounded-xl shadow-sm p-6">
        <div class="flex items-center justify-between mb-6">
          <div class="flex items-center">
            <div class="p-2 bg-blue-50 rounded-lg">
              <Table class="h-6 w-6 text-blue-500" />
            </div>
            <h2 class="text-xl font-semibold text-gray-800 ml-3">字段信息</h2>
          </div>
          <button 
            class="inline-flex items-center px-4 py-2 text-sm font-medium text-blue-600 bg-blue-50 rounded-lg hover:bg-blue-100 transition-colors duration-200"
            @click="addNewTable"
          >
            <Plus class="h-5 w-5 mr-2" />
            添加新表格
          </button>
        </div>

        <!-- 表格列表 -->
        <div class="space-y-6">
          <div v-for="(table, index) in tables" :key="index" class="border rounded-lg p-4">
            <div class="flex items-center justify-between mb-4">
              <div class="flex items-center gap-4 flex-wrap">
                <!-- 格序号和名称 -->
                <div class="flex items-center gap-2">
                  <span class="text-sm font-medium text-gray-600">表{{ index + 1}}:</span>
                  <input 
                    v-model="table.name"
                    type="text"
                    placeholder="输入表格名称"
                    class="px-2 py-1 border rounded-md text-sm w-28"
                  >
                </div>

                <!-- 表格类型名称 -->
                <div class="flex items-center gap-2">
                  <span class="text-sm text-gray-600">定义类型:</span>
                  <input 
                    v-model="table.tableName"
                    type="text"
                    :placeholder="index === 0 ? 'type_master' : 'type_detail'"
                    class="px-2 py-1 border rounded-md text-sm w-32"
                  >
                </div>

                <!-- 数组定义名称 -->
                <div class="flex items-center gap-2">
                  <span class="text-sm text-gray-600">定义数组:</span>
                  <input 
                    v-model="table.arrayName"
                    type="text"
                    :placeholder="index === 0 ? 'g_master' : 'g_detail'"
                    class="px-2 py-1 border rounded-md text-sm w-32"
                  >
                </div>

                <!-- 父表关系选择 -->
                <div v-if="index !== 0" class="flex items-center gap-2">
                  <span class="text-sm text-gray-600">父表:</span>
                  <select 
                    v-model="table.parentTable"
                    class="px-2 py-1 border rounded-md text-sm w-32"
                  >
                    <option value="">无</option>
                    <option 
                      v-for="(t, i) in tables.slice(0, index)" 
                      :key="i" 
                      :value="t.name"
                    >
                      {{ t.name }}
                    </option>
                  </select>
                </div>

                <!-- 插入表名输入框 -->
                <div class="flex items-center gap-2">
                  <span class="text-sm text-gray-600">插入表:</span>
                  <input 
                    v-model="table.insertTable"
                    type="text"
                    placeholder="输入插入表名"
                    class="px-2 py-1 border rounded-md text-sm w-32"
                  >
                </div>
              </div>

              <!-- 删除按钮 -->
              <button 
                v-if="index > 0"
                class="inline-flex items-center px-3 py-1 text-sm font-medium text-red-600 bg-red-50 rounded-lg hover:bg-red-100 transition-colors duration-200"
                @click="removeTable(index)"
              >
                <i class="ri-delete-bin-line mr-1" />
                删除表格
              </button>
            </div>

            <!-- 表格内容保持不变 -->
            <TableDetails
              :data="tableData"
              :columns="tableColumns"
              :title="`${table.name}字段配置`"
              @update:data="(newData) => updateTableData(index, newData)"
            />
          </div>
        </div>
      </div>

      <!-- 生成的代码预览 -->
      <GeneratedCode 
        v-if="isVisible && generatedCode" 
        :code-content="generatedCode" 
        :is-visible="isVisible"
        @copy-success="handleCopySuccess"
        @copy-error="handleCopyError"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed } from 'vue';
import { ElMessage } from 'element-plus';
import { Settings, Code, Table, Plus, Trash, FileText } from 'lucide-vue-next';
import GeneratedCode from '@/components/common/GeneratedCode.vue';
import ConfigurableForm from '@/components/common/ConfigurableForm.vue';
import TableDetails from '@/components/common/TableDetails.vue';
import instructions from '@/assets/auto-gp-api-instructions.md';
import { format } from 'sql-formatter';
import { autoGpApiColumns } from '@/config/tableColumns';
import { autoGpApiConfig } from '@/config/formConfigs';
import { useAutoGpApiCodeGeneration } from '@/composables/useAutoGpApiCodeGeneration';
import InstructionsCard from '@/components/common/InstructionsCard.vue';

const formConfig = autoGpApiConfig;
const localFormData = reactive({
  name: '',
  module: '',
  programId: '',
  interfaceFunction: '',
  sql: '',
  author: ''
});

const tables = ref([{ 
  name: '主表', 
  tableName: 'type_master',  // 表格类型名称
  arrayName: 'g_master',     // 数组定义名称
  parentTable: '',           // 父表关系
  insertTable: 'sfa_file',   // 新增：插入的目标表名
  data: [] 
}]);

const isVisible = ref(false);
const generatedCode = ref('');
const tableColumns = autoGpApiColumns;
const { generateAutoGpApiCode } = useAutoGpApiCodeGeneration();

const tableData = ref([]);

const updateFormData = (newValue) => Object.assign(localFormData, newValue);
const updateTableData = (index, newData) => {
  // 更新指定表格的数据
  if (tables.value[index]) {
    tables.value[index].data = newData;
    console.log('Table data updated:', tables.value[index].data);
  }
};
const addNewTable = () => {
  const detailIndex = tables.value.filter(t => t.name !== '主表').length + 1;
  const suffix = detailIndex > 1 ? detailIndex : '';
  
  tables.value.push({ 
    name: `子表${detailIndex}`,
    tableName: `type_detail${suffix}`,
    arrayName: `g_detail${suffix}`,
    parentTable: '',
    insertTable: '',  // 新增：插入的目标表名
    data: [] 
  });
};
const removeTable = (index) => tables.value.splice(index, 1);

const formatSQL = () => {
  try {
    localFormData.sql = format(localFormData.sql);
    ElMessage.success('SQL已格式化');
  } catch (error) {
    ElMessage.error('SQL格式化失败');
  }
};

const extractFields = () => {
  const selectRegex = /SELECT\s+(.+?)\s+FROM/i;
  const match = localFormData.sql.match(selectRegex);

  if (match) {
    const fields = match[1].split(',').map(field => {
      const [name, type] = field.trim().split(/\s+/);
      return {
        name: name,
        type: type || 'String',
        keyword: '10',
        defaultValue: '',
        isNull: 'Y',
        description: name,
        referenceTableField: `${name}_file.${name}`
      };
    });
    
    if (tables.value.length > 0) {
      tables.value[0].data = fields;
      console.log('更新后的表格数据:', tables.value[0].data);
      ElMessage.success('字段已提取并更新到表格中');
    }
  } else {
    ElMessage.error('无法提取字段，请检查 SQL 语句格式');
  }
};

const clearSQL = () => {
  localFormData.sql = '';
  ElMessage.info('SQL已清空');
};

const generateCode = () => {
  if (localFormData) {
    console.log('生成代码时的表格数据:', JSON.stringify(tables.value, null, 2));
    generatedCode.value = generateAutoGpApiCode(localFormData, tables.value);
    if (generatedCode.value) {
      isVisible.value = true;
    } else {
      ElMessage.warning('无法生成代码，请检查输');
    }
  }
};

const handleCopySuccess = () => ElMessage.success('代码已成功复制到剪贴板');
const handleCopyError = () => ElMessage.error('复制失败，请手动复制代码');

const sqlPreviewContent = computed(() => `\`\`\`sql\n${localFormData.sql}\n\`\`\``);
</script>

<style scoped>
:deep(.v-md-editor) {
  background-color: transparent;
}

:deep(.v-md-editor h1) {
  font-size: 1.5em;
  margin-bottom: 0.5em;
}

:deep(.v-md-editor ol) {
  padding-left: 20px;
}

:deep(.v-md-editor li) {
  margin-bottom: 0.5em;
}
</style>